package tech.xs.dao.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate5.HibernateTemplate;
import org.springframework.stereotype.Repository;

import tech.xs.dao.LeaveDao;
import tech.xs.pojo.Employee;
import tech.xs.pojo.Leave;
@Repository
public class LeaveDaoImpl implements LeaveDao {
	@Autowired
	private HibernateTemplate hibernateTemplate;
	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public List<Leave> list(Employee employee ,Date start, Date stop, Integer pageNo, Integer pageSize) {
		// TODO Auto-generated method stub
		String hql = null;
        if (employee.getSysPosition().getId() == 1) {
            hql = "from Leave where creator.id = '" + employee.getSn() + "' ";
        } else {
            hql = "from Leave where status = '待审批' and nextDeal.id = " + employee.getSn() + " ";
        }
        if (start != null) {
            String ss = new SimpleDateFormat("yyyy-MM-dd").format(start);
            hql += " and createTime > to_date('" + ss + "','YYYY-MM-DD') ";
        }
        if (stop != null) {
            String ee = new SimpleDateFormat("yyyy-MM-dd").format(stop);
            hql += " and createTime < to_date('" + ee + "','YYYY-MM-DD') ";
        }
        hql += " order by createTime desc ";
        List<Leave> LeaveList=(List<Leave>) hibernateTemplate.find(hql);
		return LeaveList;
	}

	@SuppressWarnings("deprecation")
	@Override
	public Integer count(Employee employee ,Date start, Date stop) {
		// TODO Auto-generated method stub
		String hql = null;
        if (employee.getSysPosition().getId() == 1) {
            hql = "from Leave where creator.id = '" + employee.getSn() + "' ";
        } else {
            hql = "from Leave where status = '待审批' and nextDeal.id = " + employee.getSn() + " ";
        }
        if (start != null) {
            String ss = new SimpleDateFormat("yyyy-MM-dd").format(start);
            hql += " and createTime > to_date('" + ss + "','YYYY-MM-DD') ";
        }
        if (stop != null) {
            String ee = new SimpleDateFormat("yyyy-MM-dd").format(stop);
            hql += " and createTime < to_date('" + ee + "','YYYY-MM-DD') ";
        }
        hql += " order by createTime desc ";
        return hibernateTemplate.find(hql).size();
	}

	@Override
	public void save(Leave leave) {
		// TODO Auto-generated method stub
		this.hibernateTemplate.save(leave);
	}

	@Override
	public Leave getLeave(Leave leave) {
		// TODO Auto-generated method stub
		return hibernateTemplate.get(Leave.class, leave.getId());
	}
	
	@SuppressWarnings({ "unchecked", "deprecation" })
	@Override
	public List<String> findLvType() {
		// TODO Auto-generated method stub
		return (List<String>) hibernateTemplate.find("select distinct leaveType from Leave");
	}

}
